<?php
	session_start();
	/**
	* @package admin
	* @desc This php file is used to park details inside the database.
	*/
	/**
	* @desc This include file connects to the database.
	*/
	require '../includes/connect.inc';
	//-------------------------------------------------------------------------------------------
	
	/**
	*@desc Function sanitize SQL entries, preventing sql injection.
	*@param string $s
	*/
	function sql_safe($s)
	{
		if (get_magic_quotes_gpc())
			$s = stripslashes($s);
		return mysql_real_escape_string($s);
	}
	
	//-------------------------------------------------------------------------------------------
	
	// Direct calling check
	if ($_SESSION["role"] != "admin")
	{
		header('Location: ../index.php');
		exit();
	}
	if (!isset($_POST["submit"]))
	{
		header('Location: findpark.php');
		exit();
	}
	
	
	/**
	* @desc This include file will load the directory settings for the Smarty Templates
	*/
	require '../includes/smarty.inc';
	$smarty->assign('title', "Add Park");
	$smarty->assign('user_id', $_SESSION["user_id"]);	
	$smarty->assign('last', $_SESSION["lastviewed"]);
	$smarty->assign('firstname', $_SESSION["firstname"]);
	$smarty->assign('role', $_SESSION["role"]);
	$smarty->assign('top5', $_SESSION["top5"]);	
	$smarty->assign('pathdepth', "../");
	$smarty->display('header.tpl');
	
	
	
	
	if($_POST['submit'] == "Cancel")
	{
		$name = $_SESSION['parkresults']['name'];
		$type = $_SESSION['parkresults']['type'];
		$postcode = $_SESSION['parkresults']['postcode'];
		
		unset($_SESSION['parkresults']);
		
		header("Location: ./parkresults.php?name=$name&type=$type&postcode=$postcode&submit=Find");
		exit();
	}
	else
	{
		unset($_SESSION['parkresults']);
		
		// Make arrays
		$_SESSION["errors"] = array();
		$_SESSION["form"] = array();
	
		$park_id = $_POST["park_id"];		
		$suburb_id = $_POST["suburb"];
		$park_type = $_POST["type"];
		$park_name = $_POST["name"];
		$park_address = $_POST["address"];
	
		if(!isset($_SESSION["equip"]))
			die("Old equipment was not loaded");
		else 
			$oldEquip = $_SESSION["equip"];	
		
		unset($_SESSION["equip"]);
	
	
		// Name validation	
		if(!empty($park_name))
		{
			if (!preg_match('/^[a-zA-Z0-9\s&\/,]+$/', $park_name))
				$_SESSION["errors"]["name"] = "No numbers allowed";
			else if (strlen($park_name) > 40)
				$_SESSION["errors"]["name"] = "Maximum 40 characters";
		}
		else
		{
			$_SESSION["errors"]["name"] = "Name cannot be empty";
		}
		
		//Address validation
		if(!empty($park_address))
		{
			if (!preg_match('/^[a-zA-Z0-9\s&\/,]+$/', $park_address))
				$_SESSION["errors"]["address"] = "No numbers allowed";
			else if (strlen($park_address) > 50)
				$_SESSION["errors"]["address"] = "Maximum 50 characters";
		}
		else
		{
			$_SESSION["errors"]["address"] = "Address cannot be empty";
		}
		
		//park type validation
		if(!empty($park_type))
		{
			if (!preg_match('/^[a-zA-Z\s&,]+$/', $park_type))
				$_SESSION["errors"]["type"] = "No numbers allowed";
			else if (strlen($park_type) > 30)
				$_SESSION["errors"]["type"] = "Maximum 30 characters";
		}
		else
		{
			$_SESSION["errors"]["type"] = "Type cannot be empty";
		}
		
		if(count($_POST["park_equip"]))
		{
			for($i = 0; $i < count($_POST["park_equip"]); $i++)
			{
				if(!empty($_POST[$_POST["park_equip"][$i]]))
				{
					if(!preg_match('/^[0-9]+$/', $_POST[$_POST["park_equip"][$i]]))
						$_SESSION["errors"][$_POST["park_equip"][$i]] = "Only numbers allowed";
					else if(strlen($_POST[$_POST["park_equip"][$i]]) > 11)
						$_SESSION["errors"][$_POST["park_equip"][$i]] = "Maximum 11 digits";
				}
				else
				{
					$_SESSION["errors"][$_POST["park_equip"][$i]] = "Field cannot be empty";
				}
				$_SESSION["form"][$_POST["park_equip"][$i]] = $_POST[$_POST["park_equip"][$i]];
			}
		}
		
		
		//---------------------------------------------------------------------------------------------------
		//image validations
		
		if($_FILES['pic']['size'] > 0)
		{
			$pic_name = trim(sql_safe($_FILES['pic']['name']));
			$pic_type = trim(sql_safe($_FILES['pic']['type']));
			$pic_size = trim(sql_safe($_FILES['pic']['size']));
		
			list(, , $imgtype, ) = getimagesize($_FILES['pic']['tmp_name']);
		
			if($imgtype == 3) // cheking image type
				$type = "png";
			else if($imgtype == 2)
				$type = "jpeg";
			else if($imgtype == 1)
				$type = "gif";
			else
				$_SESSION["errors"]["pic"] = "Unsupported image file";
		}
		
		// If there were any errors, show the page again
		if (count($_SESSION["errors"]))
		{
			header("Location: park.php?action=edit&id=$park_id");
			exit();
		}
		
		if($_FILES['pic']['size'] > 0)
		{
			$file = file_get_contents($_FILES['pic']['tmp_name']);
			$file = mysql_real_escape_string($file);
			
			$oldpic = "SELECT id FROM pictures WHERE id = $park_id";
			$result = mysql_query($oldpic, $connection);
			
			// Preparing data to be used in MySQL query
			if(mysql_num_rows($result) > 0)
				$query = "UPDATE pictures SET name = '$pic_name', type = '$type', size = $pic_size, file = '$file' WHERE id = $park_id";
			else
				$query = "INSERT INTO pictures (id, name, type, size, file) VALUES($park_id, '$pic_name', '$type', $pic_size, '$file')";
			
			
			mysql_query($query, $connection) or die("Could not update park picture");
		}
		
		//prepare query
		$parks_query = "UPDATE parks SET suburb_id = $suburb_id, type = \"$park_type\", name = \"$park_name\", address = \"$park_address\" WHERE park_id = $park_id";
				
		for($i = 0; $i < count($_POST["park_equip"]); $i++)
		{
			if(array_key_exists(intval($_POST["park_equip"][$i]), $oldEquip))
			{
				$query = "UPDATE parkequipment SET qty = ".$_POST[$_POST["park_equip"][$i]]." WHERE park_id = $park_id AND equip_id = ".$_POST["park_equip"][$i];
				mysql_query($query, $connection) or die("Could not update equipment".$_POST["park_equip"][$i]."update");
			}
			else
			{
				$query = "INSERT INTO parkequipment (park_id, equip_id, qty) VALUES($park_id,".$_POST["park_equip"][$i].", ".$_POST[$_POST["park_equip"][$i]].")";
				mysql_query($query, $connection) or die("Could not update equipment".$_POST["park_equip"][$i]."insert");
			}
		}
		
		if(count($_POST['park_equip']))
		{
			while (list($key, $val) = each($oldEquip))
			{
				if(!in_array($key, $_POST["park_equip"]))
					mysql_query("DELETE FROM parkequipment WHERE park_id = $park_id AND equip_id = $key", $connection) or die("Could not update equipment".$index."delete");
			}
		}
		else
		{
			mysql_query("DELETE FROM parkequipment WHERE park_id = $park_id") or die("Couldn't erase all equipment");
		}
		
		unset($_SESSION["form"]);
		unset($_SESSION["errors"]);
		
		
		//run query
		mysql_query($parks_query, $connection) or die("Could not update park details");
		
		mysql_close($connection); // Disconnect
		header("Location: ../parkdetails.php?id=$park_id");
	}	
?>